package com.whfc.emp.manager.impl;

import com.whfc.common.exception.BizException;
import com.whfc.common.face.wotu.*;
import com.whfc.common.geometry.Point;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.third.map.MapApi;
import com.whfc.common.third.map.MapLoc;
import com.whfc.emp.dao.AppEmpMapper;
import com.whfc.emp.dao.AppFaceGateFaceMapper;
import com.whfc.emp.dao.AppFaceGateMapper;
import com.whfc.emp.dao.AppFaceGatePersonMapper;
import com.whfc.emp.entity.*;
import com.whfc.emp.enums.FaceGateType;
import com.whfc.emp.enums.TaskType;
import com.whfc.emp.manager.FaceGateManager;
import com.whfc.emp.param.*;
import com.whfc.emp.redis.FaceGateApiTokenRedisDao;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description 宇泛沃土闸机平台
 * @Author hw
 * @Date 2021/1/27 14:20
 * @Version 1.0
 */
@Service("wotuFaceGateManagerImpl")
public class WotuFaceGateManagerImpl implements FaceGateManager {
    private static final Logger logger = LoggerFactory.getLogger(WotuFaceGateManagerImpl.class);

    @Autowired
    private AppEmpMapper appEmpMapper;

    @Autowired
    private AppFaceGateMapper appFaceGateMapper;

    @Autowired
    private AppFaceGatePersonMapper appFaceGatePersonMapper;

    @Autowired
    private AppFaceGateFaceMapper appFaceGateFaceMapper;

    @Autowired
    private FaceGateApiTokenRedisDao faceGateApiTokenRedisDao;

    @Autowired
    private MapApi mapApi;

    private String appId;

    private WotuFaceApi wotuFaceApi;

    /**
     * 人员注册成功
     */
    private final static String GS_SUS200 = "GS_SUS200";

    /**
     * 人员照片注册成功
     */
    private final static String GS_SUS600 = "GS_SUS600";

    /**
     * 人员授权闸机成功
     */
    private final static String GS_SUS327 = "GS_SUS327";

    /**
     * 设备不在线
     */
    private final static String GS_EXP_320 = "GS_EXP-320";

    /**
     * 设备已存在
     */
    private final static String GS_EXP_322 = "GS_EXP-322";

    /**
     * 删除闸机成功
     */
    private final static String GS_SUS302 = "GS_SUS302";

    /**
     * 闸机取消授权成功
     */
    private final static String GS_SUS330 = "GS_SUS330";

    /**
     * 闸机开门诚哥
     */
    private final static String GS_SUS900 = "GS_SUS900";

    @Override
    public void info(AppFaceGateConfig appFaceGateConfig) {
        String appId = appFaceGateConfig.getAppId();
        String appKey = appFaceGateConfig.getAppKey();
        String appSecret = appFaceGateConfig.getAppSecret();
        wotuFaceApi = new WotuFaceApi(WotuApiConst.SERVER, appId, appKey, appSecret);
        this.appId = String.valueOf(appFaceGateConfig.getId());
    }

    @Override
    public void add(AppFaceGateAddParam request) {
        String deviceKey = request.getDeviceKey();
        String name = request.getName();
        Integer deptId = request.getDeptId();
        Point point = request.getPoint();

        AppFaceGate appFaceGate = appFaceGateMapper.selectByDeviceKey(deviceKey);
        if (appFaceGate != null) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "该闸机已存在，不能重复添加！");
        }

        WotuApiResult<WotuApiAddDeviceResult> result = wotuFaceApi.deviceCreate(deviceKey, name, deptId.toString(), getToken());
        if (GS_EXP_320.equals(result.getCode())) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "设备不在线");
        }
        if (GS_EXP_322.equals(result.getCode())) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "设备已存在");
        }

        WotuApiAddDeviceResult data = result.getData();
        if (data != null) {
            AppFaceGate record = new AppFaceGate();
            BeanUtils.copyProperties(data, record);
            record.setDeptId(deptId);
            record.setName(name);
            record.setId(null);
            record.setDirection(request.getDirection());
            record.setPlatform(FaceGateType.WOTU.getCode());
            // 增加闸机位置信息
            if (point != null) {
                Double lat = point.getLat();
                Double lng = point.getLng();
                MapLoc loc = mapApi.geocode(lng, lat);
                record.setLng(lng);
                record.setLat(lat);
                record.setAddress(loc.getAddress());
            }
            appFaceGateMapper.insertSelective(record);
        }
    }

    @Override
    public void del(Integer faceGateId) {
        AppFaceGate faceGate = appFaceGateMapper.selectByPrimaryKey(faceGateId);
        if (faceGate == null) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "该闸机不存在");
        }
        Integer count = appFaceGatePersonMapper.countByFaceGateId(faceGateId);
        if (count > 0) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "该闸机下还有人员未销权，不能删除！");
        }
        String deviceKey = faceGate.getDeviceKey();
        WotuApiResult wotuApiResult = wotuFaceApi.deviceDel(deviceKey, getToken());
        if (GS_SUS302.equals(wotuApiResult.getCode())) {
            //成功
            appFaceGateMapper.deleteLogicById(faceGateId);
        }
    }

    @Override
    public String faceGateGrantEmdAdd(FaceGateGrantEmdAddParam request) {
        Integer empId = request.getEmpId();
        Integer personId = request.getPersonId();
        AppEmp appPerson = appEmpMapper.selectByPrimaryKey(empId);
        String name = appPerson.getEmpName();
        String phone = appPerson.getPhone();
        //人员注册
        WotuApiResult<WotuApiAddPersonResult> result = wotuFaceApi.personCreate(name, phone, getToken());
        if (GS_SUS200.equals(result.getCode())) {
            //人员注册成功
            WotuApiAddPersonResult data = result.getData();
            String personGuid = data.getGuid();
            appFaceGatePersonMapper.updateGrantInfo(personId, TaskType.EMP_ADD.getValue(), personGuid);
            return personGuid;
        } else {
            logger.info("人员注册失败,name:{},code:{},message:{}", name, result.getCode(), result.getMsg());
            appFaceGatePersonMapper.updateTaskType(personId, TaskType.EMP_ADD_ERROR.getValue(), "人员注册失败");
            return null;
        }
    }

    @Override
    public String faceGateGrantEmdImgAdd(FaceGateGrantEmdImgAddParam request) {
        Integer personId = request.getPersonId();
        String personGuid = request.getPersonGuid();
        String imgUrl = request.getImgUrl();
        //照片注册
        WotuApiResult<WotuApiAddFaceImgResult> faceResult = wotuFaceApi.faceImgCreate(personGuid, imgUrl, getToken());
        if (GS_SUS600.equals(faceResult.getCode())) {
            AppFaceGatePerson appFaceGatePerson = appFaceGatePersonMapper.selectByPrimaryKey(personId);
            //照片注册接口调用成功
            WotuApiAddFaceImgResult face = faceResult.getData();
            AppFaceGateFace appFaceGateFace = new AppFaceGateFace();
            appFaceGateFace.setDeptId(appFaceGatePerson.getDeptId());
            appFaceGateFace.setDeviceKey(appFaceGatePerson.getDeviceKey());
            appFaceGateFace.setEmpId(appFaceGatePerson.getEmpId());
            appFaceGateFace.setFaceGateId(appFaceGatePerson.getFaceGateId());
            appFaceGateFace.setFaceGuid(face.getGuid());
            appFaceGateFace.setFaceUrl(face.getFaceUrl());
            appFaceGateFace.setPersonGuid(personGuid);
            appFaceGateFaceMapper.insertSelective(appFaceGateFace);

            appFaceGatePersonMapper.updateTaskType(personId, TaskType.EMP_IMG_ADD.getValue(), "照片注册成功");
            return personGuid;
        } else {
            appFaceGatePersonMapper.updateTaskType(personId, TaskType.EMP_IMG_ADD_ERROR.getValue(), "照片注册失败");
            return null;
        }
    }

    @Override
    public String faceGateGrantEmdAuth(FaceGateGrantEmdAuthParam request) {
        String personGuid = request.getPersonGuid();
        String deviceKey = request.getDeviceKey();
        Integer personId = request.getPersonId();
        //闸机授权人员
        WotuApiResult result = wotuFaceApi.setPeople(deviceKey, personGuid, getToken());
        if (GS_SUS327.equals(result.getCode())) {
            appFaceGatePersonMapper.updateTaskType(personId, TaskType.EMP_AUTH.getValue(), "人员授权成功");
            return personGuid;
        } else {
            appFaceGatePersonMapper.updateTaskType(personId, TaskType.EMP_AUTH_ERROR.getValue(), "人员授权失败");
            return null;
        }
    }

    @Override
    public void faceGateBatchGrantEmpAuth(AppFaceGateGrantEmpParam request) {

    }

    @Override
    public void faceGateRevokeEmp(AppFaceGateGrantEmpParam request) {
        Integer faceGateId = request.getFaceGateId();
        List<Integer> empIdList = request.getEmpIdList();

        AppFaceGate faceGate = appFaceGateMapper.selectByPrimaryKey(faceGateId);
        if (faceGate == null) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "该闸机不存在");
        }
        String deviceKey = faceGate.getDeviceKey();
        List<String> personGuidList = new ArrayList<>();
        for (Integer empId : empIdList) {
            List<String> personGuid = appFaceGatePersonMapper.selectPersonGuidByFaceGateIdAndEmpId(faceGateId, empId);
            if (personGuid != null && personGuid.size() > 0) {
                personGuidList.addAll(personGuid);
            }
        }

        if (!personGuidList.isEmpty()) {
            String personGuids = StringUtils.join(personGuidList, ",");
            WotuApiResult wotuApiResult = wotuFaceApi.deleteSomePeople(deviceKey, personGuids, getToken());
            if (GS_SUS330.equals(wotuApiResult.getCode())) {
                //取消授权成功
                appFaceGatePersonMapper.delBYDeviceKeyAndParsonGuid(deviceKey, personGuidList);
            }
        }

    }

    @Override
    public String deviceAuthorizationPerson(String deviceKey, String name, String imgUrl) {
        WotuApiResult<WotuApiAddPersonResult> personResult = wotuFaceApi.personCreate(name, null, getToken());
        if (GS_SUS200.equals(personResult.getCode())) {
            //人员注册成功
            WotuApiAddPersonResult data = personResult.getData();
            String personGuid = data.getGuid();
            WotuApiResult<WotuApiAddFaceImgResult> faceResult = wotuFaceApi.faceImgCreate(personGuid, imgUrl, getToken());
            if (GS_SUS200.equals(faceResult.getCode())) {
                WotuApiResult result = wotuFaceApi.setPeople(deviceKey, personGuid, getToken());
                if (GS_SUS200.equals(result.getCode())) {
                    return personGuid;
                }
            }
        }
        throw new BizException(ResultEnum.FAILURE.getCode(), "人员授权失败");
    }

    @Override
    public String deviceAuthorizationCancel(String deviceKey, String personGuid) {
        String result = "";
        WotuApiResult wotuApiResult = wotuFaceApi.deleteSomePeople(deviceKey, personGuid, getToken());
        if (wotuApiResult != null) {
            result = wotuApiResult.getCode();
        }
        return result;
    }

    @Override
    public void openDoor(String deviceKey) {
        WotuApiResult wotuApiResult = wotuFaceApi.deviceInteractiveRecord(deviceKey, getToken());
        if (!GS_SUS900.equals(wotuApiResult.getCode())) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "闸机开门失败");
        }
    }

    @Override
    public void sync(Integer faceGateId) {

    }


    /**
     * 获取对应token
     *
     * @return
     */
    @Override
    public String getToken() {
        String accessToken = faceGateApiTokenRedisDao.getAccessToken(this.appId);
        if (StringUtils.isEmpty(accessToken)) {
            accessToken = wotuFaceApi.auth();
            if (StringUtils.isEmpty(accessToken)) {
                throw new BizException(ResultEnum.FAILURE.getCode(), "配置服务异常请联系管理员");
            }
            faceGateApiTokenRedisDao.setAccessToken(this.appId, accessToken);
        }
        return accessToken;
    }
}
